#!/usr/bin/perl
# $Id: outgoing.pl 43 2006-10-01 06:36:00Z cmauch $
# Author: Charles Mauch (cmauch@gmail.com)
# Description: a mailfilter to process sent email
# Legal: (c) 2006 Charles Mauch, released under the terms of the GPLv2
#
# -- [ meta information ] ----------------------------------------------------
#
#  This script simply parses through an existing mailbox, usually created by
#  mutt (the mbox) of already read email, and files those emails back into
#  the directory hierarchy established in mailfilter
#
# Assign some variables for use later.

# Load up Required Modules
use lib "/home/cpm/perl";
use lib "/home/cpm/perl/Email";
require configvars;     # Found via PERL5LIB env variable
use diagnostics;        # We like very verbose errors
use Email::Muckery;       # Folder Management
use Mail::Message;      # General Message Handling
use Email::Abstract;    #
use Email::Address;     # Detailed Address Handling
use Email::Filter;      # General Email Filtering Mechanism

my $now = localtime time;    # The current Date/Time
my ( $toemail, $fromemail );

# Turn everything into a Email::Filter object
my $item = Email::Filter->new;

# Rip out subject and drop trailing newlines if any
my $subject = $item->subject();
chomp( $subject );

# Weed out some Header Specific Stuff and assign to variables for play later
foreach $addr ( Email::Address->parse( $item->from ) ) {
    $fromemail  = $addr->address;
    $fromuser   = $addr->name;
    $fromfolder = undef;

    # If We have a name, sort normally, otherwise break down email like lists
    if ( $fromuser eq $addr->user ) {
        $fromfolder = getlistname( $fromemail );
    } else {
        $fromfolder = getfoldername( $fromuser );
    }
    chomp( $fromuser, $fromemail, $fromfolder );
} ## end foreach $addr ( Email::Address...

foreach $addr ( Email::Address->parse( $item->to ) ) {
    $touser  = $addr->name;
    $toemail = $addr->address;
    $tohost  = $addr->host;
    $tohost =~ s/\.(com|org|name)//;
    if ( $touser eq $addr->user ) {
        $tofolder = getlistname( $toemail );
    } else {
        $tofolder = getfoldername( $touser );
    }
    chomp( $touser, $toemail, $tohost, $tofolder );
} ## end foreach $addr ( Email::Address...

# For personal email addresses listed, simply file it.  We know we generate
# reasonable email.  What we're doing is filing on who we send to, which we
# don't need to loop or test for.  Just a name.

$item->accept( "$MauchConfig::maildir/personal/$tofolder" );
